package com.enqualcomm.kids.mvp.delterminal;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v4.util.SimpleArrayMap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.enqualcomm.kids.R;
import com.enqualcomm.kids.base.BaseActivity;
import com.enqualcomm.kids.bean.StringMessage;
import com.enqualcomm.kids.config.userdefault.AppDefault;
import com.enqualcomm.kids.mvp.NetworkModel;
import com.enqualcomm.kids.network.NetworkListener;
import com.enqualcomm.kids.network.SocketRequest;
import com.enqualcomm.kids.network.socket.request.ChangeTerminalOwnerParams;
import com.enqualcomm.kids.network.socket.request.DeleteTerminalParams;
import com.enqualcomm.kids.network.socket.request.QueryWatcherListParams;
import com.enqualcomm.kids.network.socket.response.BasicResult;
import com.enqualcomm.kids.network.socket.response.DeleteTerminalResult;
import com.enqualcomm.kids.network.socket.response.QueryWatcherListResult;
import com.enqualcomm.kids.network.socket.response.TerminallistResult;
import com.enqualcomm.kids.view.dialog.CommitDialogCallBack;
import com.enqualcomm.kids.view.dialog.MyCommitDialog;

import java.util.ArrayList;
import java.util.List;

import common.utils.ContactUtil;
import common.utils.DensityUtil;
import common.utils.PlatformUtil;
import common.utils.PromptUtil;
import de.greenrobot.event.EventBus;
import rx.Observable;
import rx.functions.Action1;
import rx.functions.Func1;

/**
 * Created by yinzhiqun on 2015/11/19.
 */
public class DeleteTerminalDelegateImpl implements DeleteTerminalDelegate {
    BaseActivity context;
    List<TerminallistResult.Terminal> terminals;
    SimpleArrayMap<String, List<QueryWatcherListResult.Data>> watcherMap;
    NetworkModel networkModel = new NetworkModel();

    public DeleteTerminalDelegateImpl(BaseActivity context) {
        this.context = context;
    }

    @Override
    public void setTerminals(List<TerminallistResult.Terminal> terminals) {
        this.terminals = terminals;
        getAllWatchers();
    }

    @Override
    public void onStop() {
        networkModel.onStop();
    }

    @Override
    public void getAllWatchers() {
        watcherMap = new SimpleArrayMap<>();
        //获取所有关注人信息
        Observable.from(terminals)
                .filter(new Func1<TerminallistResult.Terminal, Boolean>() {
                    @Override
                    public Boolean call(TerminallistResult.Terminal terminal) {
                        return terminal.isowner == 1;//管理员才需要获取关注人列表
                    }
                }).map(new Func1<TerminallistResult.Terminal, String>() {
            @Override
            public String call(TerminallistResult.Terminal terminal) {
                return terminal.terminalid;
            }
        }).subscribe(new Action1<String>() {
            @Override
            public void call(String terminalid) {
                getWatchers(terminalid);
            }
        });
    }

    @Override
    public void getWatchers(final String terminalid) {
        String userkey = new AppDefault().getUserkey();
        networkModel.loadDataFromServer(new SocketRequest<QueryWatcherListResult>(new QueryWatcherListParams(userkey, terminalid),
                new NetworkListener<QueryWatcherListResult>() {
                    @Override
                    public void onError(VolleyError error) {
                    }

                    @Override
                    public void onSuccess(QueryWatcherListResult response) {
                        if (response.code == 0) {
                            if (watcherMap == null) {
                                watcherMap = new SimpleArrayMap<>();
                            }
                            watcherMap.put(terminalid, response.result);
                        }
                    }
                }));
    }


    @Override
    public void doDelete(TerminallistResult.Terminal terminal, String terminalName, String imei) {
        if (terminal.isowner == 1) {
            List<QueryWatcherListResult.Data> watcherList = watcherMap.get(terminal.terminalid);
            if (watcherList != null) {
                if (watcherList.size() > 1) {
                    showListDialog(watcherList, terminal.terminalid, imei);//先移交管理员，再取消关注
                } else {
                    //管理员，没有其他关注人
                    showDeleteTerminalDialog(terminalName, terminal.terminalid);
                }
            } else {
                PromptUtil.toast(context, context.getString(R.string.try_again_later));
                //删除失败，最好再获取一遍
                getWatchers(terminal.terminalid);
            }
        } else {
            //非管理员，直接取消关注
            showDeleteTerminalDialog(terminalName, terminal.terminalid);
        }
    }

    private void showDeleteTerminalDialog(String terminalName, final String terminalid) {
        new MyCommitDialog(context, context.getString(R.string.delete_watch), context.getString(R.string.confirm_delete_watch) + terminalName + "?", new CommitDialogCallBack() {
            @Override
            public void onCommit() {
                context.showProgress();
                delete(terminalid);
            }

            @Override
            public void onCancel() {
            }
        }).show();
    }

    private void delete(String terminalid) {
        AppDefault appDefault = new AppDefault();
        String userid = appDefault.getUserid();
        String userkey = appDefault.getUserkey();
        networkModel.loadDataFromServer(new SocketRequest<DeleteTerminalResult>(new DeleteTerminalParams(userkey, userid, terminalid),
                new NetworkListener<DeleteTerminalResult>() {
                    @Override
                    public void onError(VolleyError error) {
                        context.hideProgress();
                        PromptUtil.toast(context, R.string.app_no_connection);
                    }

                    @Override
                    public void onSuccess(DeleteTerminalResult response) {
                        if (response.code == 0) {
                            if (response.ownerstatus == 2) {
                                PromptUtil.toast(context, context.getString(R.string.transfer_admin_before));
                                getAllWatchers();
                            } else {
                                EventBus.getDefault().post(new StringMessage(StringMessage.REFRESH_TERMINALLIST));
                            }
                        } else {
                            context.hideProgress();
                        }
                    }
                }));
    }

    private int ownerIndex;

    private void showListDialog(final List<QueryWatcherListResult.Data> watcherList, final String terminalid, final String imei) {//移交管理员再取消关注
        List<String> names = new ArrayList<String>();
        for (int i = 0; i < watcherList.size(); i++) {
            QueryWatcherListResult.Data queryWatcherListResult = watcherList.get(i);
            if (queryWatcherListResult.isowner != 1) {
                String contactName = ContactUtil.getContactName(context, queryWatcherListResult.phone.phonenumber);
                names.add("".equals(contactName) ? queryWatcherListResult.phone.phonenumber : contactName);
            } else {
                ownerIndex = i;
            }
        }
        final Dialog dialog = new Dialog(context, R.style.list_dialog);
        View view = LayoutInflater.from(context).inflate(R.layout.dialog_list, null);
        dialog.setContentView(view);

        WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
        lp.width = PlatformUtil.windowWidth(context) - DensityUtil.dip2px(context, 30);
        dialog.getWindow().setAttributes(lp);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));


        ListView listView = (ListView) view.findViewById(R.id.dialog_listview);
        listView.setAdapter(new MyUserListAdapter(names, context));
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                dialog.dismiss();
                int index = position;
                if (position >= ownerIndex) {
                    index++;
                }
                changeOwner(watcherList.get(index).username, terminalid, imei, watcherList.get(index).phone.phonenumber, watcherList.get(index).careuserid, watcherList.get(index).careuserkey);
            }
        });
        view.findViewById(R.id.dialog_dismiss).setOnClickListener(new View.OnClickListener() {
            public void onClick(View arg0) {
                dialog.dismiss();
            }
        });
        TextView title = (TextView) view.findViewById(R.id.dialog_title);
        title.setText(context.getString(R.string.transfer_admin));
        dialog.show();
    }

    private void changeOwner(final String phonenumber, final String terminalid, final String imei, String phone, final String careuserid, final String careuserkey) {
        //移交管理员
        new MyCommitDialog(context, context.getString(R.string.transfer_admin), context.getString(R.string.confirm_transfer_admin) + phone + " ?", new CommitDialogCallBack() {
            @Override
            public void onCommit() {
                context.showProgress();
                AppDefault appDefault = new AppDefault();
                ChangeTerminalOwnerParams params = new ChangeTerminalOwnerParams(appDefault.getUserkey(), appDefault.getUserid(),
                        terminalid, imei, phonenumber, careuserid, careuserkey);
                networkModel.loadDataFromServer(new SocketRequest<BasicResult>(params, new NetworkListener<BasicResult>() {
                    @Override
                    public void onError(VolleyError error) {
                        context.hideProgress();
                        PromptUtil.toast(context, R.string.app_no_connection);
                    }

                    @Override
                    public void onSuccess(BasicResult response) {
                        if (response.code == 0) {
                            delete(terminalid);
                        } else {
                            context.hideProgress();
                        }
                    }
                }));
            }

            @Override
            public void onCancel() {
            }
        }).show();
    }


    static class MyUserListAdapter extends BaseAdapter {
        private List<String> list;
        private Context context;

        public MyUserListAdapter(List<String> list, Context context) {
            this.list = list;
            this.context = context;
        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            TextView name_tv = null;
            if (convertView == null) {
                convertView = View.inflate(context, R.layout.change_owner_list_item, null);
                name_tv = (TextView) convertView.findViewById(R.id.dialog_listview_textview);
                convertView.setTag(name_tv);
            } else {
                name_tv = (TextView) convertView.getTag();
            }

            name_tv.setText(list.get(position));
            return convertView;
        }

    }

}
